import { app, Menu, Tray, globalShortcut } from 'electron'
import icon from '@resources/tray-icon.png?asset'
import { toggleWindowVisibility } from '@/utils'

// 创建系统托盘
export function createDefaultTray() {
  const { mainWindow } = global
  // Create tray
  const tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示/隐藏',
      click: () => toggleWindowVisibility(mainWindow),
      accelerator: 'CommandOrControl+Shift+I'
    },
    {
      label: '检查更新',
      click: () => {
        mainWindow.webContents.send('route:push', '/update')
        !mainWindow.isVisible() && mainWindow.show()
      }
    },
    {
      label: '退出',
      click: app.quit
    }
  ])
  tray.setToolTip(app.getName())
  tray.setContextMenu(contextMenu)
  tray.on('click', () => {
    if (mainWindow) {
      mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
    }
  })
  // 注册快捷键 'CommandOrControl+Shift+I'
  globalShortcut.register('CommandOrControl+Shift+I', () => {
    if (mainWindow) {
      mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
    }
  })
}
